#include "tcpfile.h"
#include "tcpserver.h"
#include "filethread.h"
#include "tcpmessage.h"

extern QString pathPre;
extern TcpFile *tcpFile;
extern TcpMessage *tcpMessage;

TcpFile::TcpFile(quint16 port)
{
    tcpServer = new TcpServer();
    hostIP = getHostIP();
    tcpPort = port;
}

// 获取IP地址
QString TcpFile::getHostIP()
{
    QList<QHostAddress> list = QNetworkInterface::allAddresses();
    foreach (QHostAddress address, list)
    {
        //我们使用IPv4地址，且不使用localhost
        if(address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress::LocalHost)
            return address.toString();
    }
    return nullptr;
}

int TcpFile::startTCP()
{
    // 转换字符串为ip
    QHostAddress addr(hostIP);
    // 开始监听
    if(!tcpServer->listen(addr, tcpPort))
    {
        qDebug() << tcpServer->errorString();
        return -1;
    }
    qDebug() << "tcp listening...";
    connect(tcpServer, SIGNAL(server_signal_incomingConnect(QString)), this, SLOT(file_slot_connected(QString)));

    return 0;
}

void TcpFile::file_slot_connected(QString socketID)
{
    qDebug() <<"new file connect..." << socketID;
    // 启动线程,传参sokect
    FileThread *t = new FileThread(tcpServer->socketArray[socketID]);
    threadMap.insert(socketID, t);
    // 移动线程
    t->moveToThread(t);
    // 开始线程
    t->start();
}

// 通过token查找socketid
QString TcpFile::findSID(QString token)
{
    QMap<QString, FileThread*>::iterator it;
    for(it = threadMap.begin(); it != threadMap.end(); ++it) {
        if(it.value()->token == token)
            return it.key();
    }
    return nullptr;
}

TcpFile::~TcpFile()
{
    tcpServer->disconnect();
    tcpServer->close();
}
